package com.lh.io.bio.chat;

import com.lh.io.bio.ExecutorService;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;

public class Server {

    //存放所有在线的连接
    private static CopyOnWriteArrayList<Socket> sockets = new CopyOnWriteArrayList<Socket>();

    public static void main(String[] args) {

        try {
            //1.监听端口号
            ServerSocket serverSocket = new ServerSocket(8888);
            ExecutorService executorService = new ExecutorService();
            Executor executor = executorService.getExecutor();

            while (true) {
                //2.等待客户端接收 会阻塞
                Socket socket = serverSocket.accept();
                //3.将在线的客户端放入到集合中
                sockets.add(socket);
                //4.接收每个客户端发送的消息
                executor.execute(() -> {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                        String msg = "";
                        while ((msg = br.readLine()) != null) {
                            //5.放给每一个客户端
                            sendClient(msg);
                        }

                    } catch (IOException e) {
                       //6.当其中客户端下线时，会进入到这里
                        //移除下线的socket
                        System.out.println("当前有人下线!");
                        sockets.remove(socket);
                    }

                });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将消息发送给每个客户端上
     * @param msg 消息
     */
    private static void sendClient(String msg) {

        sockets.forEach((socket)->{
            try {
                PrintStream print = new PrintStream(socket.getOutputStream());
                print.println(msg);
                print.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });


    }
}
